<?php

namespace app\api\middleware;

use Firebase\JWT\JWT;
use think\facade\Request;
use think\exception\HttpResponseException;
use think\Response;

class CheckToken
{
	public function handle ($request, \Closure $next)
	{
		$token = Request::header('Token');
		if ($token) {
			$key = config('jwt.key');
			JWT::$leeway = 60;
			try {
				$decoded = JWT::decode($token, $key, array('HS256'));
				$arr = (array)$decoded;
				$request->uid = $arr['data'];
				return $next($request);
			} catch (\Firebase\JWT\SignatureInvalidException $e) {
				$this->toError(1001, "签名不正确");
			} catch (\Firebase\JWT\ExpiredException $e) {
				$this->toError(1002, "token 过期");
			} catch (\Exception $e) {
				$this->toError(1003, $e->getMessage());
			}
			
		} else {
			$this->toError(1001, "token is null");
		}
		

	}


	protected function toError (int $code = 0, $msg = "", string $type = "", array $header = []): Response
	{
		$result = [
			'code' => $code,
			'msg' => $msg,
			'time' => time()
		];

		$type = $type ?: 'json';
		$response = Response::create($result, $type)->header($header);
		throw new HttpResponseException($response);
	}
}